package com.sinaapp.gavinzhang.second;

import org.junit.Test;

import java.util.HashMap;

/**
 * hashmap实现的程序计数器
 * 利用put返回值，从而减少判断次数
 * Created by gavin on 15-8-8.
 */
public class Counter {
    class VolatileInteger{
        int num = 0;
    }
    @Test
    public void greateCounter()
    {
        HashMap<String,VolatileInteger> hashMap = new HashMap<String, VolatileInteger>();
        long first = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            VolatileInteger integer = new VolatileInteger();
            integer.num = 1;
            VolatileInteger tmp = hashMap.put("1",integer);
            if (tmp != null)
            {
                //慢
                //integer.num += tmp.num;

                integer.num = tmp.num+1;
            }
        }
        System.out.println(System.currentTimeMillis()-first);
        System.out.println(hashMap.get("1").num);
    }

}
